<script setup>
import { ref, computed } from 'vue';
import { message, Modal } from 'ant-design-vue';

const inputPath = ref('');
const outputPath = ref('');
const replaceName = ref('');
const processing = ref(false);
const current = ref(0);
const total = ref(0);
const currentFile = ref('');

const databaseAddress = ref('');
const username = ref('');
const password = ref('');
const databaseName = ref('');

// 验证替换名称
const validateReplaceName = (name) => {
  const regex = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
  return regex.test(name);
};

// 检查输入是否有效
const isValid = computed(() => {
  return inputPath.value && 
         outputPath.value && 
         replaceName.value && 
         validateReplaceName(replaceName.value);
});

// 处理选择输入文件夹
const handleSelectInputPath = async () => {
  try {
    if (!window.electron?.ipcRenderer) {
      throw new Error('IPC Renderer not available');
    }
    const result = await window.electron.ipcRenderer.invoke('select-folder');
    if (!result.canceled) {
      inputPath.value = result.filePaths[0];
    }
  } catch (error) {
    console.error('选择文件夹失败:', error);
    message.error('选择文件夹失败: ' + error.message);
  }
};

// 处理选择��出文件夹
const handleSelectOutputPath = async () => {
  try {
    if (!window.electron?.ipcRenderer) {
      throw new Error('IPC Renderer not available');
    }
    const result = await window.electron.ipcRenderer.invoke('select-folder');
    if (!result.canceled) {
      outputPath.value = result.filePaths[0];
    }
  } catch (error) {
    console.error('选择文件夹失败:', error);
    message.error('选择文件夹失败: ' + error.message);
  }
};

const connectMysql = async () => {
  if (!databaseAddress.value || !username.value || !password.value) {
    message.error('请先填写数据库地址、用户名和密码');
    return;
  }

  const url = new URL(databaseAddress.value);

  const result = await window.electron.ipcRenderer.invoke('connect-mysql', {
    host: url.hostname,
    port: url.port,
    user: username.value,
    password: password.value
  });

  if (result.success) {
    message.success('连接成功');
  } else {
    message.error('连接失败: ' + result.error);
  }
}

// 处理生成按钮点击
const handleGenerate = async () => {
  if (!isValid.value) {
    Modal.error({
      title: '输入验证失败',
      content: '请确保：\n1. 已选择输入和输出文件夹\n2. 替换名称符合命名规范（字母或下划线开头，只包含字母、数字和下划线）'
    });
    return;
  }

  try {
    // 检查输出目录是否为空
    const hasFiles = await window.electron.ipcRenderer.invoke('check-directory', outputPath.value);
    
    if (hasFiles) {
      // 显示确认对话框
      const shouldContinue = await window.electron.ipcRenderer.invoke('show-confirm-dialog');
      if (!shouldContinue) {
        return;
      }
    }

    processing.value = true;
    current.value = 0;
    total.value = 0;
    currentFile.value = '';

    // 调用主进程处理文件替换
    const [host, port] = databaseAddress.value.split(':');

    const result = await window.electron.ipcRenderer.invoke('process-files', {
      inputPath: inputPath.value,
      outputPath: outputPath.value,
      replaceName: replaceName.value,
      dbOption: {
        database: databaseName.value,
        host: host,
        port: port,
        username: username.value,
        password: password.value
      }
    });

    // 监听进度更新
    window.electron.ipcRenderer.on('process-progress', (data) => {
      current.value = data.current;
      total.value = data.total;
      currentFile.value = data.currentFile;
    });

    if (result.success) {
      message.success('处理完成！');
    } else {
      throw new Error(result.error);
    }
  } catch (error) {
    console.error('处理失败:', error);
    message.error('处理失败: ' + error.message);
  } finally {
    processing.value = false;
  }
};
</script>

<template>
  <div class="container">
    <a-card class="main-card" :bordered="false">
      <div class="page-header">
        <h2 class="page-title">生成实体</h2>
        <p class="page-description">通过模板快速生成代码，提高开发效率</p>
      </div>

      <div class="config-section">
        <h3 class="section-title">配置信息</h3>
        <div class="path-inputs">
          <div class="input-group">
            <span class="input-label">输入文件夹：</span>
            <a-input
              v-model:value="inputPath"
              placeholder="请选择模板所在文件夹"
              class="path-input"
              :disabled="processing"
            >
              <template #addonAfter>
                <a-button 
                  type="primary" 
                  @click="handleSelectInputPath"
                  :disabled="processing"
                >
                  选择文件夹
                </a-button>
              </template>
            </a-input>
          </div>

          <!-- <div class="input-group">
            <span class="input-label">输入文件夹：</span>
            <a-input
              v-model:value="inputPath"
              placeholder="请选择模板所在文件夹"
              class="path-input"
              :disabled="processing"
            >
              <template #addonAfter>
                <a-button 
                  type="primary" 
                  @click="handleSelectInputPath"
                  :disabled="processing"
                >
                  选择文件夹
                </a-button>
              </template>
            </a-input>
          </div>
           -->
          <div class="input-group">
            <span class="input-label">输出文件夹：</span>
            <a-input
              v-model:value="outputPath"
              placeholder="请选择输出文件夹"
              class="path-input"
              :disabled="processing"
            >
              <template #addonAfter>
                <a-button 
                  type="primary" 
                  @click="handleSelectOutputPath"
                  :disabled="processing"
                >
                  选择文件夹
                </a-button>
              </template>
            </a-input>
          </div>

          <div class="input-group">
            <span class="input-label">替换名称：</span>
            <a-input
              v-model:value="replaceName"
              placeholder="请输入替换名称（字母或下划线开头，只能包含字母、数字和下划线）"
              class="path-input"
              :disabled="processing"
              :status="replaceName && !validateReplaceName(replaceName) ? 'error' : ''"
            />
          </div>

          <div class="input-group">
            <span class="input-label">数据库地址：</span>
            <a-input
              v-model:value="databaseAddress"
              placeholder="请输入数据库地址"
              class="path-input"
              :disabled="processing"
            />
          </div>

          <div class="input-group">
            <span class="input-label">用户名：</span>
            <a-input
              v-model:value="username"
              placeholder="请输入用户名"
              class="path-input"
              :disabled="processing"
            />
          </div>

          <div class="input-group">
            <span class="input-label">密码：</span>
            <a-input
              v-model:value="password"
              placeholder="请输入密码"
              class="path-input"
              :disabled="processing"
              type="password"
            />
          </div>

          <div class="input-group">
            <span class="input-label">数据库名称：</span>
            <a-input
              v-model:value="databaseName"
              placeholder="请输入数据库名称"
              class="path-input"
              :disabled="processing"
            />
          </div>
        </div>
      </div>

      <div class="action-section">
        <a-button 
          type="primary" 
          @click="handleGenerate" 
          class="btn-generate"
          :loading="processing"
          :disabled="!isValid"
        >
          {{ processing ? '处理中...' : '开始生成' }}
        </a-button>

        <div v-if="processing" class="progress-info">
          <a-progress 
            :percent="total ? (current / total) * 100 : 0" 
            :status="current === total ? 'success' : 'active'"
          />
          <div class="progress-text">
            处理进度：{{ current }}/{{ total }}
          </div>
          <div class="current-file">
            当前处理：{{ currentFile }}
          </div>
        </div>
      </div>
    </a-card>
  </div>
</template>

<style scoped>
.container {
  width: 100%;
}

.main-card {
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03), 
              0 1px 6px -1px rgba(0, 0, 0, 0.02), 
              0 2px 4px rgba(0, 0, 0, 0.02);
}

.page-header {
  margin-bottom: 32px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.page-title {
  margin: 0 0 8px;
  color: rgba(0, 0, 0, 0.88);
  font-weight: 600;
  font-size: 20px;
  line-height: 1.4;
}

.page-description {
  margin: 0;
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
}

.section-title {
  font-size: 16px;
  color: rgba(0, 0, 0, 0.88);
  margin-bottom: 24px;
}

.path-inputs {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.input-group {
  display: flex;
  align-items: center;
  gap: 16px;
}

.input-label {
  min-width: 90px;
  text-align: right;
  color: rgba(0, 0, 0, 0.88);
  font-size: 14px;
}

.path-input {
  flex: 1;
  min-width: 0;
}

.action-section {
  margin-top: 32px;
  text-align: center;
  padding: 0 16px 16px;
}

.progress-info {
  margin-top: 24px;
  max-width: 800px;
  margin-left: auto;
  margin-right: auto;
  padding: 0 16px;
}

.progress-text {
  margin-top: 12px;
  color: #666;
  font-size: 14px;
}

.current-file {
  margin-top: 8px;
  color: #999;
  font-size: 13px;
  word-break: break-all;
}

.btn-generate {
  min-width: 120px;
  height: 40px;
  font-size: 16px;
}

@media (max-width: 768px) {
  .input-group {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .input-label {
    text-align: left;
    margin-bottom: 4px;
  }

  .path-input {
    width: 100%;
  }
}

:deep(.ant-input) {
  border-radius: 4px;
}

:deep(.ant-input-group-addon) {
  padding: 0;
  border: none;
}

:deep(.ant-input-group-addon .ant-btn) {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

:deep(.ant-card-body) {
  padding: 24px;
}

@media (prefers-color-scheme: dark) {
  .main-card {
    background: #1f1f1f;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  }

  .section-title {
    color: #fff;
  }

  .input-label {
    color: #d9d9d9;
  }

  .progress-text {
    color: #d9d9d9;
  }

  .current-file {
    color: #8c8c8c;
  }
}
</style>
